﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Channels;
using System.IO;

namespace suanpan.API.Components.Encoders
{
    public class JsonpEncoder : MessageEncoder
    {
        private MessageEncoder _encoder;

        public JsonpEncoder()
        {
            WebMessageEncodingBindingElement element = new WebMessageEncodingBindingElement();
            _encoder = element.CreateMessageEncoderFactory().Encoder;
        }

        public override string ContentType
        {
            get
            {
                return _encoder.ContentType;
            }
        }

        public override string MediaType
        {
            get
            {
                return _encoder.MediaType;
            }
        }

        public override MessageVersion MessageVersion
        {
            get
            {
                return _encoder.MessageVersion;
            }
        }

        public override Message ReadMessage(ArraySegment<byte> buffer, BufferManager bufferManager, string contentType)
        {
            return _encoder.ReadMessage(buffer, bufferManager, contentType);
        }

        public override Message ReadMessage(System.IO.Stream stream, int maxSizeOfHeaders, string contentType)
        {

            return _encoder.ReadMessage(stream, maxSizeOfHeaders, contentType);
        }

        public override ArraySegment<byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset)
        {
            throw new NotImplementedException();
        }

        public override void WriteMessage(Message message, System.IO.Stream stream)
        {
            string jsonMethod = (string)message.Properties["jsonMethod"];
            if ( jsonMethod == null )
            {
                _encoder.WriteMessage(message, stream);
                return;
            }

            WriteToStream(stream, jsonMethod + "( ");
            _encoder.WriteMessage(message, stream);
            WriteToStream(stream, " );");
        }

        public void WriteToStream(Stream stream, string content)
        {
            using ( StreamWriter sw = new StreamWriter(stream) )
            {
                sw.Write(content);
            }
        }

    }


}
